<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择科目" prop="chapterId">
        <el-select v-model="queryParams.chapterId" placeholder="请选择科目" style="width: 100%;">
          <el-option v-for="item in chapterList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题目内容" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入题目内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList">
      <!-- 序号 -->
      <el-table-column type="index" label="序号" width="60px"></el-table-column>
      <el-table-column label="科目名称" prop="chapterId">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.chapter.name || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="题目内容" prop="content" width="500px">
        <template slot-scope="scope">
          <div style="background-color: #f2f2f2; padding: 5px 12px;font-size: 12px;text-align: left;">
            {{ scope.row.content }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="难度等级" align="center" prop="difficulty">
        <template slot-scope="scope">
          <el-tag
            type="danger"
            effect="plain"
            size="mini"
          >
            {{ scope.row.difficulty }}级
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分值" prop="score">
        <template slot-scope="scope">
          <span style="color: #f50; font-weight: bolder;font-size: 18px">{{ scope.row.score }}</span> <span
          style="color: #999; font-size: 12px;"
        >分</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="small-padding fixed-width" width="140px">
        <template slot-scope="scope">
          <div>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </div>
          <el-button
            size="mini"
            type="text"
            @click="openOptionDialog(scope.row)"
          >题目选项
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择科目" prop="chapterId">
          <el-select v-model="form.chapterId" placeholder="请选择科目" style="width: 100%;">
            <el-option v-for="item in chapterList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容">
          <el-input type="textarea" :rows="3" v-model="form.content" placeholder="请输入题目内容"/>
          <!-- 查重按钮 -->
          <div style="margin-top: 16px;">
            <el-alert
              title="查重时可以把题目中的图片、音频、视频等内容去除，只保留文字信息。"
              type="info" :closable="false"
            >
            </el-alert>
            <div style="margin-top: 16px;">
              <el-button type="warning" plain size="small" @click="checkContent">内容查重</el-button>
            </div>
          </div>

        </el-form-item>
        <el-form-item label="难度等级" prop="difficulty">
          <el-input v-model="form.difficulty" type="number" placeholder="请输入难度等级"/>
        </el-form-item>
        <el-form-item label="分值" prop="score">
          <el-input v-model="form.score" type="number" placeholder="请输入分值"/>
        </el-form-item>
        <el-form-item label="答案解析" prop="analyze">
          <el-input v-model="form.analyze" type="textarea" rows="3" placeholder="请输入答案解析"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 题目选项弹出层 -->
    <el-dialog title="题目选项" center :visible.sync="openOption" width="640px" append-to-body>
      <!-- 选项列表 -->
      <el-table :data="questionOptionList" style="width: 100%;">
        <el-table-column label="序号" prop="content" width="80px">
          <template slot-scope="scope">
            <div style="font-size: 12px;font-weight: bold;">
              {{ scope.row.label }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="选项内容" prop="content">
          <template slot-scope="scope">
            <el-input type="textarea" :rows="2" v-model="scope.row.content" placeholder="请输入选项内容"/>
          </template>
        </el-table-column>
        <el-table-column label="正确答案" align="center" prop="isRight" width="100px">
          <template slot-scope="scope">
            <i v-if="scope.row.isCorrect === 1" class="el-icon-success" style="font-size: 16px;color: #1ab394;"></i>
            <el-button v-else size="small" type="text" @click="setCorrect(scope.row)">设置正确答案</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleOptionAdd">保存修改</el-button>
        <el-button size="small" @click="cancelOption">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addQuestion, delQuestion, getQuestion, listQuestion, updateQuestion } from '@/api/app/question'
import { listChapter } from '@/api/app/subject'
import { listOption, addAndEdit } from '@/api/app/question-option'

export default {
  name: 'Question',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目表格数据
      questionList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openOption: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chapterId: null,
        content: null
      },
      // 表单参数
      form: {},
      chapterList: [],
      questionOptionList: [],
      correct: 1,
      // 表单校验
      rules: {
        chapterId: [
          { required: true, message: '科目ID不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '题目内容不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getChapterList()
  },
  methods: {

    getChapterList() {
      listChapter({ pageSize: 100 }).then(resp => {
        this.chapterList = resp.rows
      })
    },

    /** 查询题目列表 */
    getList() {
      this.loading = true
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        chapterId: this.queryParams.chapterId,
        content: null,
        difficulty: 1,
        score: 1,
        analyze: null
      }
      this.resetForm('form')
    },

    /**
     * 内容查重
     */
    checkContent() {
      if (!this.form.content) {
        this.$message.error('请先输入题目内容')
        return
      }
      listQuestion({ content: this.form.content }).then(resp => {
        if (resp.total > 0) {
          this.$message.error('题目内容重复，请重新编辑')
        }
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加题目'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改题目'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQuestion(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addQuestion(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除题目编号为"' + ids + '"的数据项？').then(function() {
        return delQuestion(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },

    openOptionDialog(row) {
      const id = row.id
      // 获取题目选项
      listOption({ questionId: id }).then(resp => {
        this.openOption = true
        if (resp.rows.length === 0) {
          this.questionOptionList = [
            { questionId: id, label: 'A', content: '', isCorrect: 0 },
            { questionId: id, label: 'B', content: '', isCorrect: 0 },
            { questionId: id, label: 'C', content: '', isCorrect: 0 }
          ]
          return
        }
        this.questionOptionList = resp.rows
        console.info(this.questionOptionList)
      })
    },

    handleOptionAdd() {
      const checkContent = this.questionOptionList.every(item => item.content.trim() && item.content.length > 0)
      console.info(checkContent)
      if (!checkContent) {
        this.$message.error('选项内容不能为空')
        return
      }
      const checkCorrect = this.questionOptionList.some(item => item.isCorrect === 1)
      if (!checkCorrect) {
        this.$message.error('请设置正确答案')
        return
      }
      addAndEdit(this.questionOptionList).then(resp => {
        this.openOption = false
        this.$modal.msgSuccess('保存成功')
      })
    },

    cancelOption() {
      this.questionOptionList = []
      this.openOption = false
    },

    setCorrect(row) {
      this.questionOptionList = this.questionOptionList.map(item => {
        return {
          ...item,
          isCorrect: item.label === row.label ? 1 : 0
        }
      })
      console.log(this.questionOptionList)
    }
  }
}
</script>
